<template>
  <a-modal :width="1200" v-model:visible="showDetail" title="订单详情" title-align="start" :mask-closable="false" @cancel="closedDialog">
    <div class="purchase-order-detail">
      <div class="header">
        <p class="title">基础信息</p>
      </div>
      <a-row class="detail-item">
        <a-col :span="10">
          <div class="flex">
            <p class="label">采购订单号：</p>
            <div class="flex-c">
              <span class="highlight">{{ detailInfo.billNo }}</span>
              <CopyText style="margin-left: 5px" :val="detailInfo.billNo" />
            </div>
          </div>
        </a-col>
        <a-col :span="7">
          <div class="flex">
            <p class="label">状态：</p>
            <p class="val">{{ statusMap[detailInfo.status] }}</p>
          </div>
        </a-col>
        <a-col :span="7">
          <div class="flex">
            <p class="label">结算方式：</p>
            <p class="val">{{ settleAccounts[detailInfo.settleType] }}</p>
          </div>
        </a-col>
      </a-row>
      <template v-if="source == 'purchase'">
        <a-row class="detail-item">
          <a-col :span="10">
            <div class="flex">
              <p class="label">需求人：</p>
              <p class="val">{{ detailInfo.salesmanName }}</p>
            </div>
          </a-col>
          <a-col :span="7">
            <div class="flex">
              <p class="label">创建人：</p>
              <p class="val">{{ detailInfo.createUname }}</p>
            </div>
          </a-col>
          <a-col :span="7">
            <div class="flex">
              <p class="label">创建时间：</p>
              <p class="val">{{ $setTime(detailInfo.gmtCreate) }}</p>
            </div>
          </a-col>
        </a-row>
        <a-row class="detail-item">
          <a-col :span="10">
            <div class="flex">
              <p class="label">供应商：</p>
              <p class="val">{{ detailInfo.supplierName }}</p>
            </div>
          </a-col>
          <a-col :span="7">
            <div class="flex">
              <p class="label">收货仓库：</p>
              <p class="val">{{ detailInfo.warehouseName }}（{{ detailInfo.warehouseCode }}）</p>
            </div>
          </a-col>
          <a-col :span="7">
            <div class="flex">
              <p class="label">采购员：</p>
              <p class="val">{{ detailInfo.purchaseUname }}</p>
            </div>
          </a-col>
        </a-row>
      </template>
      <template v-if="source == 'supplier'">
        <a-row class="detail-item">
          <a-col :span="10">
            <div class="flex">
              <p class="label">采购方：</p>
              <p class="val">{{ detailInfo.companyName }}</p>
            </div>
          </a-col>
          <a-col :span="7">
            <div class="flex">
              <p class="label">采购员：</p>
              <p class="val">{{ detailInfo.createUname }}</p>
            </div>
          </a-col>
          <a-col :span="7">
            <div class="flex">
              <p class="label">提交时间：</p>
              <p class="val">{{ $setTime(detailInfo.gmtAudit) }}</p>
            </div>
          </a-col>
        </a-row>
      </template>
      <a-row class="detail-item">
        <a-col :span="10">
          <div class="flex">
            <span class="label" style="flex-shrink: 0">附件：</span>
            <ul style="margin-right: 10px" v-if="detailInfo.attachment">
              <li v-for="(url, i) in detailInfo.attachment.split(',')" style="margin-bottom: 4px" :key="i">
                <a-tag color="arcoblue" class="cursor" @click="downloadFile(url)">
                  <span>{{ url }}</span>
                  <icon-to-bottom />
                </a-tag>
              </li>
            </ul>
            <p v-else>--</p>
          </div>
        </a-col>
        <a-col :span="14">
          <div class="flex">
            <span class="label">备注：</span>
            <span style="flex: 1">{{ detailInfo.remark }}</span>
          </div>
        </a-col>
      </a-row>
      <div class="purchase-detail-order">
        <a-table class="table-two-line show-border-table" ref="tableRef" :data="detailInfo.billItems" :scroll="{ x: '100%', y: '100%' }" size="mini" :pagination="false">
          <template #columns>
            <a-table-column data-index="img" title="图片" :width="60" fixed="left">
              <template #cell="{ record }">
                <ImgPopover :src="record.productImg">
                  <template #con>
                    <a-image width="50" height="50" fit="contain" :src="record.productImg" />
                  </template>
                </ImgPopover>
              </template>
            </a-table-column>
            <a-table-column data-index="productName" title="产品名称" :width="100" fixed="left">
              <template #cell="{ record }">
                <TextLimit :val="record.productName || '--'" />
              </template>
            </a-table-column>
            <a-table-column data-index="sku" title="SKU" :width="120" fixed="left">
              <template #cell="{ record }">
                <p>{{ record.sku }}</p>
                <div v-if="record.urgent" class="urgent">急</div>
              </template>
            </a-table-column>
            <a-table-column data-index="productSpecs" title="规格名" :width="120">
              <template #cell="{ record }">
                <p>{{ getProductSpecs(record) }}</p>
              </template>
            </a-table-column>
            <a-table-column data-index="space" title="采购参数" :width="150">
              <template #cell="{ record }">
                <PurchasePropPopover v-if="record.purchaseSpecsArr" :purchaseSpecsArr="record.purchaseSpecsArr" />
              </template>
            </a-table-column>
            <a-table-column data-index="remark" title="备注" :width="100" />
            <a-table-column data-index="gmtExpectDelivery" title="期望交期" :width="90">
              <template #cell="{ record }">
                <p>{{ $setTime(record.gmtExpectDelivery, 'YYYY/MM/DD') }}</p>
              </template>
            </a-table-column>
            <a-table-column data-index="purchaseAmt" title="采购数量" :width="70" />
            <a-table-column data-index="materialPrice" title="材质单价(元/g)" :width="100" />
            <a-table-column data-index="productPrice" title="产品单价" :width="70" />
            <a-table-column data-index="laborPrice" title="工费单价" :width="70" />
            <a-table-column data-index="rate" title="税率" :width="70">
              <template #cell="{ record }">
                <p>{{ record.rate }}%</p>
                <p class="highlight">{{ record.priceType == 1 ? '含税' : '不含税' }}</p>
              </template>
            </a-table-column>
            <a-table-column data-index="planNo" title="申购单号" :width="120" v-if="source == 'purchase'">
              <template #cell="{ record }">
                <p class="highlight">{{ record.planNo }}</p>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
    </div>
    <template #footer>
      <a-space>
        <a-button class="gray-outline" @click="closedDialog">取消</a-button>
        <a-popover v-model:popup-visible="showPoper" trigger="click" @popup-visible-change="rejectMsg = null">
          <template #content>
            <p>请填写拒单理由：</p>
            <a-textarea style="width: 300px; height: 100px" v-model="rejectMsg" placeholder="请输入" allow-clear />
            <div style="text-align: right">
              <a-space>
                <a-button class="gray-outline" size="mini" @click="showPoper = false">取消</a-button>
                <a-button type="primary" size="mini" @click="submitData(false)" :loading="submitLoading">确认</a-button>
              </a-space>
            </div>
          </template>
          <a-button class="gray-outline">拒单</a-button>
        </a-popover>
        <a-button type="primary" @click="submitData(true)" :loading="submitLoading">确认接单</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue'
  import { getPurchaseOrderInfo, receivePurchaseOrder } from '@/api/purchaseApplication'
  import { parseJson } from '@/utils'
  import PurchasePropPopover from './purchasePropPopover.vue'
  import { Message } from '@arco-design/web-vue'
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    source: {
      type: String,
      default: 'purchase',
    },
    currentId: {
      type: String,
    },
  })

  const statusMap = {
    0: '已作废',
    1: '草稿中',
    10: '待审核',
    11: '已驳回',
    20: '待接单',
    21: '已拒单',
    30: '采购中',
    40: '已完成',
  }
  const settleAccounts = {
    1: '月结',
    2: '现货',
    3: '现款',
  }
  const showDetail = ref(props.isShow)
  const detailInfo = ref<any>({})
  const rejectMsg = ref()
  const showPoper = ref(false)
  const submitLoading = ref(false)

  // 关闭
  function closedDialog() {
    showDetail.value = false
    emit('closed')
  }

  // 获取详情
  async function getDetail() {
    if (!props.currentId) return
    const res: any = await getPurchaseOrderInfo({ id: props.currentId })
    detailInfo.value = res?.data || {}
    detailInfo.value.billItems.forEach((item: any) => {
      let purchaseSpecs = item.purchaseSpecs ? parseJson(item.purchaseSpecs, {}) : {}
      item.purchaseSpecsArr = Object.values(purchaseSpecs)
    })
  }
  getDetail()
  //  下载
  function downloadFile(url: string) {
    let _url = url
    if (_url.indexOf('?') > -1) {
      _url += '&response-content-type=application/octet-stream'
    } else {
      _url += '?response-content-type=application/octet-stream'
    }
    let link = document.createElement('a')
    link.href = _url
    link.click()
  }
  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
  // 确认
  async function submitData(status: Boolean) {
    if (!status && !rejectMsg.value) {
      Message.error('请填写拒收原因！')
      return
    }
    let _params: any = {
      ids: [props.currentId],
      pass: status,
    }
    if (!status) {
      _params.remark = rejectMsg.value
    }
    submitLoading.value = true
    const res: any = await receivePurchaseOrder(_params)
    submitLoading.value = false
    if (res) {
      Message.success(status ? '接单成功' : '已拒绝接单')
      emit('success')
      closedDialog()
    }
  }
</script>

<style lang="less" scoped>
  .purchase-order-detail {
    height: calc(84vh - 160px);
    display: flex;
    flex-direction: column;
    .header {
      font-size: 14px;
      font-weight: bold;
      margin-bottom: 10px;
      border-left: 3px solid rgba(var(--primary-6), 0.5);
      padding-left: 10px;
      .title {
        margin-right: 30px;
        width: 90px;
      }
    }
    .purchase-detail-order {
      margin-top: 20px;
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
    .detail-item {
      margin-bottom: 5px;
      .label {
        width: 120px;
        text-align: right;
      }
      .val {
        color: #666;
      }
      .info {
        font-size: 12px;
        color: #999;
      }
    }
    .product-info {
      margin-left: 5px;
    }
    .urgent {
      font-size: 12px;
      display: inline-block;
      background-color: red;
      color: #fff;
      width: 18px;
      border-radius: 50%;
      line-height: 18px;
      text-align: center;
      transform: scale(0.82);
    }
  }
</style>
